import { API_URL, CODE, MyAjax } from '../config';

export const set_user_token = 'set_user_token';

export function function_login (email, password, dispatch, cb) {
  MyAjax(API_URL.login, {
    email: email,
    password: password
  }, (result) => {
    cb(result);
    if (result.code === CODE.SUCCESS) {
      dispatch({
        type: set_user_token,
        uid: result.data.uid,
        token: result.data.token,
        timestamp: result.data.timestamp,
        organizeid: result.data.organizeid
      });
    }
  });
}

export function function_handlelogout(){
  sessionStorage.setItem("redirect_page", window.location);
}

export function function_logout (dispatch) {
  window.localStorage.removeItem("_uid");
  window.localStorage.removeItem("_organizeid");
  window.localStorage.removeItem("_timestamp");
  window.localStorage.removeItem("_token");
  dispatch({
    type: set_user_token,
    uid: 0,
    token: "",
    timestamp: 0,
    organizeid: 0
  });
}

export function function_register (companyName, nickName, email, password, dispatch, cb) {
  MyAjax(API_URL.register, {
    organizeName: companyName,
    nickName: nickName,
    email: email,
    password: password
  }, (result) => {
    cb(result);
    if (result.code === CODE.SUCCESS) {
      dispatch({
        type: set_user_token,
        uid: result.data.uid,
        token: result.data.token,
        timestamp: result.data.timestamp,
        organizeid: result.data.organizeid
      });
    }
  });
}

export function function_snedverify_email (email, imageCode, cb) {
  MyAjax(API_URL.sendVerifyEmail, {
    email,
    imageCode
  }, (result) => {
    cb(result);
  })
}

export function function_set_password (password, cb) {
  MyAjax(API_URL.chgPwdByUid, {
    password
  }, (result) => {
    cb(result);
  })
}

export function function_chgpwd_by_email (email, imageCode, emailCodes, pwd, cb) {
  MyAjax(API_URL.chgPwdByEmail, {
    email,
    imageCode,
    emailCodes,
    pwd
  }, (result) => {
    cb(result);
  })
}